/*
 * @(#)MaintWorkflowAssignProgressUserAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.web;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.calendar.bean.CalendarRecord;
import com.dcivision.calendar.dao.CalendarRecordDAObject;
import com.dcivision.framework.ApplicationContainer;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.SysFunction;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.staff.bean.StaffRecord;
import com.dcivision.staff.dao.StaffRecordDAObject;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.workflow.bean.MtmWfProgressWfProgress;
import com.dcivision.workflow.bean.MtmWorkflowDynamicUserActor;
import com.dcivision.workflow.bean.MtmWorkflowStepUserActor;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.core.WorkflowProgressManager;
import com.dcivision.workflow.core.WorkflowRetrievalManager;
import com.dcivision.workflow.dao.MtmWfProgressWfProgressDAObject;
import com.dcivision.workflow.dao.MtmWorkflowDynamicUserActorDAObject;
import com.dcivision.workflow.dao.MtmWorkflowStepUserActorDAObject;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;
import com.dcivision.workflow.dao.WorkflowStepDAObject;

/**
  MaintWorkflowAssignProgressUserAction.java

  This class is for maint user role.

    @author          Angus Shiu
    @company         DCIVision Limited
    @creation date   29/07/2003
    @version         $Revision: 1.38 $
*/

public class MaintWorkflowAssignProgressUserAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.38 $";


  /** Creates a new instance of MaintWorkflowAssignProgressUserAction */
  public MaintWorkflowAssignProgressUserAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.workflow.dao.WorkflowProgressDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_TASK);
  }

  /**
   * clearUniqueFields
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void clearUniqueFields(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintWorkflowProgressForm workflowProgressForm = (MaintWorkflowProgressForm) form;
    workflowProgressForm.setID(null);
  }

  /**
   * getObjectType
   *
   * @return  The corresponding object type of permission setup action.
   */
  public String getObjectType() {
    return(GlobalConstant.OBJECT_TYPE_WORKFLOW);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    log.debug("at AssignAction nav Mode: "+maintForm.getNavMode() + ", op Mode: "+maintForm.getOpMode());
            
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    log.debug( ((maintForm!=null) ? maintForm.getClass().getName() : "")+", OP Mode:"+opMode+", Nav Mode:"+navMode);

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);  if (forward!=null) {return forward;}
    
    WorkflowRetrievalManager retrievalManager = new WorkflowRetrievalManager(this.getSessionContainer(request), this.getConnection(request));
    WorkflowProgressDAObject workflowProgressDAO = new WorkflowProgressDAObject(this.getSessionContainer(request),this.getConnection(request));
    MaintWorkflowProgressForm progressForm = (MaintWorkflowProgressForm)form;
    
    
    HashMap stepMap = (HashMap) ((request.getAttribute("assignStepMap")!=null)? request.getAttribute("assignStepMap") : request.getSession().getAttribute("assignStepMap"));
    HashMap userListMap = new HashMap();
    HashMap userGroupListMap = new HashMap();
    HashMap userRoleListMap = new HashMap();

    
    MtmWorkflowStepUserActorDAObject mtmWfStepUserActorDAO = new MtmWorkflowStepUserActorDAObject(this.getSessionContainer(request), this.getConnection(request));
    WorkflowStepDAObject stepDAO=new WorkflowStepDAObject(this.getSessionContainer(request), this.getConnection(request));
    
    String filterBy = request.getParameter("filterBy");

    if (stepMap!=null) {    	
      Set keySet = stepMap.keySet();
      Iterator iterator = keySet.iterator();
      while (iterator.hasNext()) {
        Integer stepID = (Integer) iterator.next(); 
        WorkflowStep step=(WorkflowStep)stepDAO.getObjectByID(stepID);
        if(!Utility.isEmpty(filterBy)){        
          step.setFilterBy(Integer.valueOf(filterBy));
          stepDAO.updateObject(step);
        }
        
        WorkflowProgress workflowProgress = (WorkflowProgress) stepMap.get(stepID);
        Integer trackID=workflowProgress.getTrackID();
        Integer submitterID = workflowProgressDAO.getUserIDForWorkflowTrackSubmitter(trackID);
        String[] submitterFilterByIDs = null;
        if(!Utility.isEmpty(step.getFilterBy())){
          submitterFilterByIDs = this.getSubmitterFilterByID(step.getFilterBy(),submitterID,request);
        }

        List mtmActorList = mtmWfStepUserActorDAO.getListByWorkflowStepID(stepID,MtmWorkflowStepUserActor.ACTION_TYPE_EXECUTION,step.getFilterBy(),submitterFilterByIDs);
        List userList = retrievalManager.getUserRecordListForStepAssignment(mtmActorList,stepID);
        List groupList = retrievalManager.getUserGroupListForStepAssignment(mtmActorList,stepID);
        List roleList = retrievalManager.getUserRoleListForStepAssignment(mtmActorList,stepID);
        
        if(Utility.isEmpty(userList) && Utility.isEmpty(groupList) && Utility.isEmpty(roleList)){
          UserRecordDAObject userDAO = new UserRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
          UserGroupDAObject groupDAO = new UserGroupDAObject(this.getSessionContainer(request),this.getConnection(request));
          UserRoleDAObject roleDAO = new UserRoleDAObject(this.getSessionContainer(request),this.getConnection(request));
          userList = userDAO.getFullList();
          groupList = groupDAO.getFullList();
          roleList = roleDAO.getFullList();
        }
        userListMap.put(stepID, userList);
        userGroupListMap.put(stepID, groupList);
        userRoleListMap.put(stepID, roleList);
      }
    }
    if(!Utility.isEmpty(opMode) && opMode.equals(GlobalConstant.OP_MODE_UPDATE)){
    	request.setAttribute("update", "yes");    	
    }
    if (((stepMap == null || stepMap!=null) && GlobalConstant.NAV_MODE_EDIT.equals(navMode))){
      stepMap = new HashMap();
      String workflowProgressIDStr = request.getParameter("ID");
      Integer workflowProgressID = null;
      WorkflowProgress workflowProgress = null;
      WorkflowStep workflowStep =null;
      //WorkflowProgressDAObject workflowProgressDAO = new WorkflowProgressDAObject(this.getSessionContainer(request),this.getConnection(request));
      MtmWfProgressWfProgressDAObject childParentDAObject = new MtmWfProgressWfProgressDAObject(this.getSessionContainer(request),this.getConnection(request));
      WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.getSessionContainer(request),this.getConnection(request));

      if (!Utility.isEmpty(workflowProgressIDStr)) {
        workflowProgressID = new Integer(workflowProgressIDStr);
      }
//      if (!Utility.isEmpty(trackIDStr)){
//        trackID = new Integer(trackIDStr);
//      }

      //List workflowProgressList = workflowProgressDAO.getListByTrackIDAndStatus(trackID,WorkflowProgress.STATUS_PENDING);
      List workflowProgressList = childParentDAObject.getListByParentProgressID ( workflowProgressID );
      if (!Utility.isEmpty(workflowProgressList)) {
        for ( int i = 0 ; i < workflowProgressList.size() ; i++ ) {
          MtmWfProgressWfProgress mtmWfProgressWfProgress= (MtmWfProgressWfProgress)workflowProgressList.get(i);
          workflowProgress = (WorkflowProgress)workflowProgressDAO.getObjectByID(mtmWfProgressWfProgress.getChildProgressID());
          workflowStep = (WorkflowStep)workflowStepDAO.getObjectByID(workflowProgress.getWorkflowStepID());
          workflowProgress.setWorkflowStepSource(workflowStep);
          stepMap.put(workflowStep.getID(),workflowProgress);
          Set keySet = stepMap.keySet();
          Iterator iterator = keySet.iterator();
          while (iterator.hasNext()) {
            Integer stepID = (Integer) iterator.next();
            List mtmActorList = mtmWfStepUserActorDAO.getListByWorkflowStepID(stepID);
            List userList = retrievalManager.getUserRecordListForStepAssignment(mtmActorList,stepID);
            List groupList = retrievalManager.getUserGroupListForStepAssignment(mtmActorList,stepID);
            List roleList = retrievalManager.getUserRoleListForStepAssignment(mtmActorList,stepID);
            
            if(Utility.isEmpty(userList) && Utility.isEmpty(groupList) && Utility.isEmpty(roleList) ){
              UserRecordDAObject userDAO = new UserRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
              UserGroupDAObject groupDAO = new UserGroupDAObject(this.getSessionContainer(request),this.getConnection(request));
              UserRoleDAObject roleDAO = new UserRoleDAObject(this.getSessionContainer(request),this.getConnection(request));
              userList = userDAO.getFullList();
              groupList = groupDAO.getFullList();
              roleList = roleDAO.getFullList();
            }
            userListMap.put(stepID, userList);
            userGroupListMap.put(stepID, groupList);
            userRoleListMap.put(stepID, roleList);
          }
        }
//        request.setAttribute("returnUrl","workflow/ListWorkflowTask.do");
        navMode = GlobalConstant.NAV_MODE_NEW;
      }

    }
    request.setAttribute("userListMap", userListMap);
    request.setAttribute("userGroupListMap", userGroupListMap);
    request.setAttribute("userRoleListMap", userRoleListMap);
    
    request.getSession().setAttribute("assignStepMap", stepMap);
/***********************************************************
//  This is commented by Lun
//  This will create duplicated record if the user select dynamic owner
//  right after he/she finished the task  ( not through post-process )
//
//    if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
//      this.updateRecord(mapping,maintForm,request,response);
//    }
//
//  End commented by Lun
************************************************************/

    return super.execute(mapping, form, request, response);
  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	//  This is commented by Lun
  	//    this.createWorkflowProgressUserRecord(mapping, form, request, response);
  	this.updateRecord ( mapping, form, request, response );
  	// End commented by Lun

  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    WorkflowProgressDAObject workflowProgressDAO = new WorkflowProgressDAObject(this.getSessionContainer(request), this.getConnection(request));
    WorkflowStepDAObject stepDAO = new WorkflowStepDAObject(this.getSessionContainer(request),this.getConnection(request));
    WorkflowProgressManager workflowProgressManager = new WorkflowProgressManager(this.getSessionContainer(request), this.getConnection(request));
    MtmWfProgressWfProgressDAObject mtmWfProgressWfProgressDAO = new MtmWfProgressWfProgressDAObject(this.getSessionContainer(request),this.getConnection(request));
    
    WorkflowProgress prevProgress = new WorkflowProgress();
    this.createWorkflowProgressUserRecord(mapping, form, request, response);
    
    String workflowProgressID = request.getParameter("workflowProgressID");
    //create job where notification rule for task arrived/before due date/over due date,
    //current workflowProgress owner is Assign At Runtime
    workflowProgressManager.createNotificationWhenTaskArrived(new Integer(workflowProgressID));
    
    if(!Utility.isEmpty(workflowProgressID)){
      Integer currentWfProgressID = new Integer(workflowProgressID);
      WorkflowProgress currentProgress = (WorkflowProgress) workflowProgressDAO.getObjectByID(currentWfProgressID);
      /*
      Integer trackID = currentProgress.getTrackID();
      List progressList = workflowProgressDAO.getListByTrackID(trackID);
      int curProgressSeqNo = currentProgress.getSeqNo().intValue();
      WorkflowProgress prevProgress = (WorkflowProgress) progressList.get((curProgressSeqNo-1)-1);
      */
      //    TODO get pre progress through MTM_WF_PROGRESS_WF_PROGRESS
      List parentProgressList = mtmWfProgressWfProgressDAO.getListByChildProgressID(currentProgress.getID());
      if (!Utility.isEmpty(parentProgressList)) {
        MtmWfProgressWfProgress mtmWfProgressWfProgress = (MtmWfProgressWfProgress)parentProgressList.get(parentProgressList.size()-1);
        prevProgress = (WorkflowProgress)workflowProgressDAO.getObjectByID(mtmWfProgressWfProgress.getParentProgressID());
      }
      Integer parentWfProgressID = prevProgress.getID();
      WorkflowProgress workflowProgress = (WorkflowProgress)workflowProgressDAO.getObjectByID(parentWfProgressID);
      if (!Utility.isEmpty(workflowProgress)) {
        workflowProgress.setPostProgress("");
      }

      workflowProgress = (WorkflowProgress)workflowProgressDAO.updateObject(workflowProgress);

      //add calendar record
      String progressID[] = TextUtility.splitString ( request.getParameter("workflowProgress"), ";" );
      for ( int i = 0 ; i < progressID.length ; i++ ) {
log.debug("Creating calendar record for progress id="+progressID[i]);
        currentProgress = (WorkflowProgress)workflowProgressDAO.getObjectByID( Integer.valueOf(progressID[i]) );
        WorkflowStep childStep = (WorkflowStep)stepDAO.getObjectByID(currentProgress.getWorkflowStepID() );
        Timestamp endDate;
        if (childStep.getOnNoResponseFor() != null
              || childStep.getOnNoResponseAfter() != null
              || ((GlobalConstant.TRUE.equals(childStep.getAllowAssignDueDate()) || WorkflowStep.DYNAMIC_ASSIGN_DUE_DATE_MANDATORY.equals(childStep.getAllowAssignDueDate())) && !Utility.isEmpty(currentProgress.getDueDate()) ) ){
          if ((GlobalConstant.TRUE.equals(childStep.getAllowAssignDueDate()) || WorkflowStep.DYNAMIC_ASSIGN_DUE_DATE_MANDATORY.equals(childStep.getAllowAssignDueDate())) && !Utility.isEmpty(currentProgress.getDueDate())){
            endDate = currentProgress.getDueDate();
          } else if (childStep.getOnNoResponseAfter() != null){
            endDate = childStep.getOnNoResponseAfter();
          } else {
            endDate = Utility.addDay(Utility.getCurrentTimestamp(),childStep.getOnNoResponseFor().intValue());
            Calendar tmpDate = Utility.timestampToCalendar(endDate);
            //Utility.setCalendarTime(tmpDate, 23, 59, 59, 0);
            endDate = Utility.calendarToTimestamp(tmpDate);
            // Commented by Brook.Huang. Mask working calendar count for [EIP-941].
            // if (!Utility.isEmpty(childStep.getOnNoResponseCalendarID()) ) {
            // HolidayManager holidayManager = new HolidayManager(this.getSessionContainer(request), this.getConnection(request));
            // endDate = holidayManager.getDueDateEndDate(Utility.getCurrentTimestamp(), childStep.getOnNoResponseFor().intValue()*24*60*60*1000, new
            // Integer(childStep.getOnNoResponseCalendarID()) );
            //            } 
          }
log.debug ( "endDate="+endDate);
          CalendarRecordDAObject calendarRecordDAObject = new CalendarRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
          WorkflowRecordDAObject workflowRecordDAObject = new WorkflowRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
          ApplicationContainer applicationContainer = (ApplicationContainer)request.getSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
          SysFunction sysFunction = applicationContainer.getSysFunctionByFunctionCode(SystemFunctionConstant.SCHEDULE);
          if ( sysFunction!=null && "A".equals(sysFunction.getStatus()) ){
            WorkflowRecord workflowRecord = (WorkflowRecord)workflowRecordDAObject.getObjectByID(childStep.getWorkflowRecordID());
            MtmWorkflowDynamicUserActorDAObject dynamicUserDAO = new MtmWorkflowDynamicUserActorDAObject(this.getSessionContainer(request),this.getConnection(request));
            List userList = dynamicUserDAO.getDynamicUserIDListByWorkflowProgressID(currentProgress.getID());
            for (int k=0;k<userList.size();k++){
              CalendarRecord calendarRecord = new CalendarRecord();
             //calendarRecord.setAlertType("I");
log.debug ( "Creating calendar record for user id="+userList.get(k).toString());
              calendarRecord.setCreatorID((Integer)userList.get(k));
              calendarRecord.setUpdaterID((Integer)userList.get(k));
              calendarRecord.setDatetime(endDate);
              calendarRecord.setEndtime(endDate);
              calendarRecord.setEventType(CalendarRecord.EVENT_TYPE_CALENDAR_TODO);
              calendarRecord.setPriority(currentProgress.getProgressPriority());
              calendarRecord.setObjectID(currentProgress.getID());
              calendarRecord.setObjectType(CalendarRecord.OBJECT_TYPE_WORKFLOW);
              calendarRecord.setReminderType(",");
              calendarRecord.setTitle(MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(), "calendar.label.pending_workflow_task")+":" +workflowRecord.getWorkflowCode()+ "/" + childStep.getStepSeq() + "."+childStep.getStepName());
              calendarRecord.setDetail(childStep.getDescription());
              calendarRecord.setShareType(CalendarRecord.SHARE_TYPE_PRIVATE );
              calendarRecord.setStatus(GlobalConstant.FALSE);
              calendarRecordDAObject.insert(calendarRecord);
           }
          }
        }else{
log.debug ( "currentProgress.getID()="+currentProgress.getID());
log.debug ( "childStep.getID()="+childStep.getID());
log.debug ( "childStep.getOnNoResponseFor()="+childStep.getOnNoResponseFor());
log.debug ( "childStep.getOnNoResponseAfter()="+childStep.getOnNoResponseAfter());
log.debug ( "childStep.getAllowAssignDueDate()="+childStep.getAllowAssignDueDate());
        }
      }

      this.commit(request);
    }
  }

  /**
   * create the Mtm_Wf_Progress_User_Record record & Mtm_Wf_Dynamic_User_Actor record
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void createWorkflowProgressUserRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {log.debug("insert record in MaintWorkflowAssignProgressUserAction");

    String workflowProgressIDStr = request.getParameter("workflowProgress");
    String[] workflowProgressIDAry = TextUtility.splitString(workflowProgressIDStr, ";");
    for (int j=0; !Utility.isEmpty(workflowProgressIDAry) && j < workflowProgressIDAry.length; j++) {
      String allPermisisonData = request.getParameter("allPermissionData_" + workflowProgressIDAry[j]);
      log.debug("the workflowProgressIDAry[" + j + "] is>>>> " + allPermisisonData);
       //create user actor for the step
      String permData = TextUtility.replaceString(allPermisisonData, "\r", "");
      String[] tmpAry = TextUtility.splitString(permData, "\n");
      if (tmpAry == null) {
        tmpAry = new String[0];
      }
      //* specific user account
      for (int i = 0; i < tmpAry.length; i++) {
        if (!Utility.isEmpty(tmpAry[i])) {
          String[] rowAry = TextUtility.splitString(tmpAry[i], "\t");
//        insert it into Mtm_WF_Dynamic_User_Actor table
          this.insertDynamicUserAcotr(new Integer(workflowProgressIDAry[j]),
                 rowAry[2],
                 new Integer(rowAry[0]), rowAry[3], request);
       }
      }    
    }   
  }

  /**
   * get progress user record list by progress group array and insert dynamic user actor record
   * @param progressGroupAry
   * @param request
   * @return
   * @throws ApplicationException
   */
  /*
  private List getProgressUserListByProgressGroupArray(String[] progressGroupAry, List progressUserList, HttpServletRequest request )
      throws ApplicationException {
    MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAO = new MtmUserRecordUserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));

    String progressID,groupID;
    List tmpGroupIDList = new ArrayList();
    for(int i=0; !Utility.isEmpty(progressGroupAry) && i<progressGroupAry.length; i++){
      int delimiterIndex = progressGroupAry[i].indexOf("_");
      progressID = progressGroupAry[i].substring(0, delimiterIndex);
      groupID = progressGroupAry[i].substring(delimiterIndex+1);

      //insert it into Mtm_WF_Dynamic_User_Actor table
      this.insertDynamicUserAcotr(TextUtility.parseIntegerObj(progressID),
            MtmWorkflowStepUserActor.ACTOR_TYPE_GROUP,
            TextUtility.parseIntegerObj(groupID),request);

      List tmpUserIDList = mtmUserRecordUserGroupDAO.getUserIDListByUserGroupID(TextUtility.parseIntegerObj(groupID ));
      for(int j=0; j<tmpUserIDList.size(); j++){
        String tmpProgressUser = progressID + "_" + tmpUserIDList.get(j).toString();
        if(Utility.isEmpty(progressUserList) || progressUserList.indexOf(tmpProgressUser) < 0 ){
          progressUserList.add(tmpProgressUser);
        }
      }
    }

    return progressUserList;
  }
  */

  /**
   * get progress user record list by progress role array and insert dynamic user actor record
   * @param progressRoleAry
   * @param progressUserList
   * @param request
   * @return
   * @throws ApplicationException
   */
  /*
  private List getProgressUserListByProgressRoleArray(String[] progressRoleAry, List progressUserList, HttpServletRequest request )
      throws ApplicationException {
    MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO = new MtmUserRecordUserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
    String progressID,roleID;
    List tmpRoleIDList = new ArrayList();
    for(int i=0; !Utility.isEmpty(progressRoleAry) && i<progressRoleAry.length; i++){
      int delimiterIndex = progressRoleAry[i].indexOf("_");
      progressID = progressRoleAry[i].substring(0, delimiterIndex);
      roleID = progressRoleAry[i].substring(delimiterIndex+1);

      //insert it into Mtm_WF_Dynamic_User_Actor table
      this.insertDynamicUserAcotr(TextUtility.parseIntegerObj(progressID),
            MtmWorkflowStepUserActor.ACTOR_TYPE_ROLE,
            TextUtility.parseIntegerObj(roleID), request);

      List tmpUserIDList = mtmUserRecordUserRoleDAO.getUserIDListByUserRoleID(TextUtility.parseIntegerObj(roleID) );
      for(int j=0; j<tmpUserIDList.size(); j++){
        String tmpProgressUser = progressID + "_" + tmpUserIDList.get(j).toString();
        if(Utility.isEmpty(progressUserList) || progressUserList.indexOf(tmpProgressUser) < 0 ){
          progressUserList.add(tmpProgressUser);
        }
      }
    }

    return progressUserList;
  }
  */

  /**
   * insert a record into Mtm_WF_Dynamic_User_Actor table
   * @param workflowProgressID
   * @param actorType
   * @param actorID
   * @param request
   * @throws ApplicationException
   */
  private void insertDynamicUserAcotr(
        Integer workflowProgressID,
        String actorType,
        Integer actorID,
				String permission,
        HttpServletRequest request)throws ApplicationException {
    MtmWorkflowDynamicUserActorDAObject dynamicDAO = new MtmWorkflowDynamicUserActorDAObject(this.getSessionContainer(request), this.getConnection(request));
    MtmWorkflowDynamicUserActor tmpDynamic = new MtmWorkflowDynamicUserActor();
    tmpDynamic.setWorkflowProgressID(workflowProgressID);
    tmpDynamic.setActorType(actorType);
    tmpDynamic.setActorID(actorID);
    tmpDynamic.setPermission(permission);
    dynamicDAO.insertObject(tmpDynamic);
  }
  
  /**
   * for filter user record.
   * @param filterBy
   * @param submitterID
   * @param request
   * @return
   * @throws ApplicationException
   */
  private String[] getSubmitterFilterByID(Integer filterBy,Integer submitterID,HttpServletRequest request) throws ApplicationException{
    UserGroupDAObject userGroupDAO = new UserGroupDAObject(this.getSessionContainer(request),this.getConnection(request));
    UserRoleDAObject userRoleDAO = new UserRoleDAObject(this.getSessionContainer(request),this.getConnection(request));
    StaffRecordDAObject staffRecordDAO = new StaffRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    String[] submitterIDFilterByID = null;
    
    if(new Integer(WorkflowStep.STEP_FILTERBY_GROUP).equals(filterBy)){
      List userGroupList = userGroupDAO.getListByUserRecordIDGroupType(submitterID,"P");
      submitterIDFilterByID = new String[userGroupList.size()];
      for(int i=0;i<userGroupList.size();i++){
        UserGroup userGroup = (UserGroup)userGroupList.get(i);
        submitterIDFilterByID[i] = userGroup.getID().toString();
      }
    }else if(new Integer(WorkflowStep.STEP_FILTERBY_ROLE).equals(filterBy)){
      List userRoleList = userRoleDAO.getListByUserRecordID(submitterID);
      submitterIDFilterByID = new String[userRoleList.size()];
      for(int i=0;i<userRoleList.size();i++){
        UserRole userRole = (UserRole)userRoleList.get(i);
        submitterIDFilterByID[i] = userRole.getID().toString();
      }
    }else {
      StaffRecord staffRecord = (StaffRecord)staffRecordDAO.getObjectByUserRecordID(submitterID);
      Method getFileMth=null;
      submitterIDFilterByID = new String[1];
      try{
        getFileMth = staffRecord.getClass().getMethod("getLevel"+filterBy.intValue()+"ID",null); 
        Integer levelID = (Integer)getFileMth.invoke(staffRecord, new Object[]{});
        if(!Utility.isEmpty(levelID)){
          submitterIDFilterByID[0] = levelID.toString();
        }
      }catch(NoSuchMethodException ex){
        log.error(ex,ex);
      }catch(IllegalAccessException ee){
        log.error(ee,ee);
      }catch(InvocationTargetException e){
        log.error(e,e);
      }    
    }
    
    return submitterIDFilterByID;
    
  }

  
}
